package game;

import java.awt.Color;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.demoweb.model.dao.ScoreDao;
import com.demoweb.model.dao.MemberDao;
import com.demoweb.model.dto.Member;
import com.demoweb.model.dto.Score;


public class CopyOfMainScreen extends JPanel implements Runnable {

	private Image flappyImage, enemyImage, backImage;
	private Font gameover, score;

	long prevCulTime = 0, currentTime = 0, pipeResponTime = 0;
	long prevPipeCreationTime = 0;
	private int flyint = 0, overlapInt = 0, scoreInt = 0;
	private boolean START = false, GAMESTOP = false, RESTARTER = false, login = false;
	final static int pipe_Responer = 1500;
	String a,b;
	LinkedList<BackGround> backOb = new LinkedList<BackGround>();
	LinkedList<Enemy> pipe = new LinkedList<Enemy>();
	Score dbdto = new Score();
	ScoreDao dbDao = new ScoreDao();
	MemberDao dao = new MemberDao();
	Member gamelogin = null;
	Flappy flappy;
	BackGround bg;
	Member member;
	Thread thread;
	
	public CopyOfMainScreen() {

		prevCulTime = System.currentTimeMillis();
		currentTime = System.currentTimeMillis();

		gameover = new Font("Verdana", Font.BOLD, 60);
		score = new Font("Verdana", Font.BOLD, 20);
		
		try {

			URL url = getClass().getResource("/image/flappyfish.png");
			Image origin = ImageIO.read(url);
			flappyImage = origin.getScaledInstance(50, 40, Image.SCALE_SMOOTH);

			url = getClass().getResource("/image/stone.png");
			origin = ImageIO.read(url);
			enemyImage = origin.getScaledInstance(60, 490, Image.SCALE_SMOOTH);

			url = getClass().getResource("/image/back3.png");
			origin = ImageIO.read(url);
			backImage = origin.getScaledInstance(800, 600, Image.SCALE_SMOOTH);

		} catch (IOException e) {
			e.printStackTrace();
		}

		/**
		 * 배경 이미지를 패널과 좌,우측에 3개를 만듬
		 */
		for (int i = 0; i < 3; i++) {
			bg = new BackGround(backImage);
			backOb.add(bg);
			backOb.get(i).setX(800 * i - 800);
		}

		flappy = new Flappy(flappyImage);

		this.addKeyListener(new KeyAdapter() {

			@Override
			public void keyPressed(KeyEvent e) {
				super.keyPressed(e);

				if (e.getKeyCode() == KeyEvent.VK_P) {
					RESTARTER = true;
				}
				START = true;
				if (flyint > 0)
					overlapInt = 1;
				else if (flyint == 0) {
					overlapInt = 0;
					flyint = 0;

				}
			}
		});
		
		while(!login){
			
			a = JOptionPane.showInputDialog("아이디를 입력하시요"); //숫자를 하나 입력받아 정수로 변환
			b =   JOptionPane.showInputDialog("비밀번호를 입력하시요"); //숫자를 하나 입력받아 정수로 변환

			if(a.equals("p") || b.equals("p")){
				
				login = true;
				
			}
			
			MemberDao mdao = new MemberDao();
			Member member = mdao.getMemberByIdAndPasswd(a, b);
			
			if (member == null) {
				// 로그인 실패
				System.out.println("로그인 실패");
				continue;
			} else {
				// 로그인 성공
				System.out.println("로그인 성공");
				login = true;
				thread = new Thread(this);
				thread.start();
				flappy.setX(0);
				break;
			}
		}
	}

	public void InitializationMath() {

		prevCulTime = 0;
		currentTime = 0;
		pipeResponTime = 0;
		prevPipeCreationTime = 0;
		flyint = 0;
		overlapInt = 0;
		scoreInt = 0;
		START = false;
		GAMESTOP = false;
		RESTARTER = false;
		pipe.clear();
		flappy.setX(0);
		flappy.setY(200);
		prevCulTime = System.currentTimeMillis();
		currentTime = System.currentTimeMillis();
		flappy.setDy(0);
		flappy.setUy(15);
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		for (BackGround bak : backOb) {

			bak.render(g);

		}

		flappy.render(g);

		for (Enemy eneeee : pipe) {

			eneeee.render(g);

		}

		/**
		 * 문자 출력
		 */
		Graphics2D g2d = (Graphics2D) g;

		g2d.setFont(score);
		g2d.setColor(Color.red);
		g2d.drawString("SCORE : " + scoreInt, 500, 50);

		if (GAMESTOP == true) {
			g2d.setFont(gameover);// 폰트 설정
			g2d.setColor(Color.orange);
			// 현재 폰트 기준으로 지정된 문자열이 출력될 사각형 반환
			Rectangle2D rect = g2d.getFontMetrics().getStringBounds(
					"YOUR SCORE IS ", g2d);
			int x = (backImage.getWidth(null) - (int) rect.getWidth()) / 2;
			int y = (backImage.getHeight(null) - (int) rect.getHeight()) / 2;
			g2d.drawString("GAME OVER!!!", x, y);

			rect = g2d.getFontMetrics().getStringBounds("Your Score is ***!!",
					g2d);

			int xX = (backImage.getWidth(null) - (int) rect.getWidth()) / 2;
			int yY = ((backImage.getHeight(null) - (int) rect.getHeight()) / 2)
					+ (int) rect.getHeight();
			g2d.drawString("Your Score is " + scoreInt + "!!", xX, yY);

		}

	}

	/**
	 * 파이프의 위치와, 파이프 사이의 거리를 결정하는 메서드
	 */
	public void pipeMath(int i, int ranNum) {

		Enemy enene = new Enemy(enemyImage);
		enene.active = true;
		enene.setX(880);

		if (i == 0) {
			enene.setY((int) (Math.random() * 50) - 450 + ranNum);
		} else if (i == 1) {
			enene.setY((int) (Math.random() * 50) + 200 + ranNum);
		}
		pipe.add(enene);
	}

	@Override
	public void run() {

		while (true) {
			if (GAMESTOP == false) {
				/**
				 * 화면 바깥으로의 이동 제한
				 */
				if (flappy.getY() < 0
						|| flappy.getY() > backImage.getHeight(null)
								- flappyImage.getHeight(null)) {

					GAMESTOP = true;
					dbdto.setMemberId(a);
					dbdto.setScore(scoreInt);
					dbdto.setGameNo(3);
					dbDao.insertScore(dbdto, 3);
				}

				/**
				 * 현재 시간 생성
				 */
				if (currentTime - prevCulTime < 1200) {
					currentTime = System.currentTimeMillis();
				}

				/**
				 * 배경 이동
				 */
				for (BackGround b : backOb) {

					b.update();
					if (b.getX() < -800)
						b.setX(800);
				}

				/**
				 * 생성된 파이프 이동
				 */
				for (int i = pipe.size() - 1; i >= 0; i--) {

					Enemy enen = pipe.get(i);
					enen.update();
					if (flappy.getX() / 10 == enen.getX() / 10) {
						scoreInt += 50;
					}

					if (enen.active == false)
						pipe.remove(enen);

				}
				/**
				 * 일정 시간마다 파이프 생성
				 */
				long current22Time = System.currentTimeMillis();// 현재 시간
				if (current22Time - prevPipeCreationTime > pipe_Responer) {

					int r = 150 * (int) (Math.random() * 3);

					for (int i = 0; i < 2; i++) {
						pipeMath(i, r);
					}
					prevPipeCreationTime = current22Time;
				}
				/**
				 * 충돌 체크
				 */
				for (int i = pipe.size() - 1; i >= 0; i--) {

					Rectangle rect1 = pipe.get(i).getArea();

					Rectangle flapRect = flappy.getArea();

					if (flapRect.intersects(rect1)) {

						GAMESTOP = true;
						dbdto.setMemberId(a);
						dbdto.setScore(scoreInt);
						dbdto.setGameNo(3);
						dbDao.insertScore(dbdto, 3);
						break;
					}

				}
				pipeResponTime = System.currentTimeMillis();

				/**
				 * 시작후 잠깐동안 일정 높이에서 앞으로 전진, 그 후의 케릭터 조작 구문
				 */
				if (currentTime - prevCulTime < 1200) {

					currentTime = System.currentTimeMillis();
					flappy.Startupdate();

				} else {
					if (START == true) {
						if (flyint > 0 && overlapInt == 1) {
						}
						flyint++;
						flappy.update2();
						flappy.setDy(0);
						if (flyint >= 15) {

							START = false;
							flyint = 0;
							flappy.setUy(15);

						}
					} else if (START == false)
						flappy.update1();

				}

				repaint();

				try {
					Thread.sleep(30);
				} catch (Exception ex) {
				} finally {

				}

			} else if (GAMESTOP == true && RESTARTER == true) {

				InitializationMath();

			}
			
			thread.yield();
		}
	}
}
